package at.ac.tuwien.dse.health.event.listener;

import at.ac.tuwien.dse.health.event.bus.EventTarget;
import at.ac.tuwien.dse.health.event.type.Event;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * Uses reflection to notify {@link EventTarget EventTargets} about {@link Event Events}.
 *
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class LocalEventListener implements EventListener {
	private static final Logger LOGGER = LogManager.getFormatterLogger(LocalEventListener.class);

	@Override
	@Transactional
	public void handleEvent(EventTarget eventTarget, Event<? extends Serializable> event) {
		try {
			eventTarget.invoke(event);
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Delivered event %s to %s", event, eventTarget);
			}
		} catch (Exception e) {
			LOGGER.error("Cannot deliver event %s to %s", event, eventTarget);
			LOGGER.catching(e);
		}
	}
}
